<template>
  <el-dialog v-model="dialogVisible" width="500" :title="bt.Titlename">
    <el-form :model="AddForm" label-width="auto" style="max-width: 600px">
      <el-form-item label="商品名称:">
        <el-select v-model="AddForm.sId">
          <el-option label="请选择" :value="0" />
          <el-option v-for="itme in options" :label="itme.shop_Name" :value="itme.shop_Id" />
        </el-select>
      </el-form-item>

      <el-form-item label="生产批次:">
        <el-input v-model="AddForm.rabit_Batch" type="text" maxlength="30" :disabled="bt.bsf" placeholder="生产批次自动生成"/>
      </el-form-item>

      <el-form-item label="保质期(天):">
        <el-input v-model="AddForm.rabit_Shelflife" type="text" maxlength="5" />
      </el-form-item>

      <el-form-item label="生产许可证号:">
        <el-input v-model="AddForm.rabit_Shencan" type="text" maxlength="30" />
      </el-form-item>

      <el-form-item label="生产企业:">
        <el-input v-model="AddForm.rabit_Company" type="text" />
      </el-form-item>

      <el-form-item label="封面图:">
        <el-upload class="avatar-uploader" action="http://localhost:5094/api/Fileall/Fileup" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <div style="position: relative; display: inline-block;">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="max-width: 200px; max-height: 200px;"
              alt="Preview Image" />
            <el-icon v-if="imageUrl" class="avatar-delete-icon" @click.stop="removeImage"
              style="position: absolute; top: 0; right: 0; cursor: pointer; background: rgba(255,255,255,0.7); border-radius: 50%;">
              <Close />
            </el-icon>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit()">{{ bt.bname }}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog v-model="LogExport" width="500">
    <el-form :model="ExportCouts" label-width="auto" style="max-width: 600px">
      <el-form-item label="导出数量:">
        <el-input v-model="ExportCouts.cout" type="text" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="AllExport()">导出</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-button type="primary" @click="handleAdd()">新增</el-button>
  <el-button type="primary" @click="AllDel" :disabled="addIds.length === 0">
    删除
  </el-button>
  <el-table :data="tableData" border style="width: 1500px" @selection-change="handleSelectionChange">

    <el-table-column prop="rabit_Id" label="序号" width="auto">
      <template v-slot="scope">
        <el-checkbox-group v-model="addIds">
          <el-checkbox :value="scope.row.rabit_Id">{{ scope.row.rabit_Id }}</el-checkbox>
        </el-checkbox-group>
      </template>
    </el-table-column>
    <el-table-column prop="shop_Name" label="商品名称" width="200px" />
    <el-table-column prop="rabit_Batch" label="生产批次" width="auto" />
    <el-table-column prop="rabit_Shelflife" label="保质期(天)" width="auto" />
    <el-table-column prop="rabit_Shencan" label="生产许可证号" width="auto" />
    <el-table-column prop="rabit_Company" label="生产企业" width="auto" />
    <el-table-column prop="rabit_Infomation" label="信息完善度" width="auto" />
    <el-table-column prop="creater" label="创建人" width="auto" />
    <el-table-column prop="createTime" label="创建时间" width="auto">
      <template v-slot="scope">
        {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
    </el-table-column>
    <el-table-column prop="updater" label="修改人" width="auto" />
    <el-table-column prop="updateTime" label="修改时间" width="auto">
      <template v-slot="scope">
        <span v-if="scope.row.updateTime != null">
          {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="400px">
      <template v-slot="scope">
        <el-button type="primary" @click="RabitsDetail(scope.row)">详情</el-button>
        <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
        <el-button type="primary" @click="ExportEdit()">导出溯源码</el-button>
        <el-button type="danger" @click="handleDelete(scope.row.rabit_Id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, roleTypes } from 'element-plus'
import axios from 'axios'
import { Plus, Close } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import moment from 'moment'
const ExportCouts = ref({
  cout: 0
})
//溯源表单
const AddForm = ref({
  rabit_Id: 0,
  sId: 0,
  rabit_Batch: "",
  rabit_Shelflife: 0,
  rabit_Shencan: "",
  rabit_Company: "",
  rabit_Infomation: "",
  rabit_TitleImg: "",
  rabit_IsDel: false,
  creater: localStorage.getItem("Name") ?? "",
  updater: "",
})
//溯源列表
const tableData = ref([{
  rabit_Id: 0,
  shop_Id: 0,
  shop_Name: "",
  rabit_Batch: "",
  rabit_Shelflife: 0,
  rabit_Shencan: "",
  rabit_Company: "",
  rabit_Infomation: "",
  rabit_TitleImg: "",
  rabit_IsDel: false,
  creater: "",
  createTime: "",
  updater: "",
  updateTime: ""
}])
//对话框
const dialogVisible = ref(false)
const LogExport = ref(false)
///头像上传方法
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  AddForm.value.rabit_TitleImg = response.data;
}//图片验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('只能传jpg类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}//删除图片
const removeImage = () => {
  imageUrl.value = ''
  AddForm.value.rabit_TitleImg = ''
}//选中数据id集合
const addIds = ref<any>([])
//商品下拉框
const options = ref([{
  "shop_Id": 0,
  "shop_Name": ""
}])//按钮数据
const bt = reactive({
  bid: 0,
  bname: "",
  Titlename: "",
  bsf:false
})
onMounted(() => {
  Show()
  ShowShop()
})
//溯源显示
const Show = () => {
  axios.get('http://localhost:5094/api/RabitsAll/ShowRaibts').then(res => {
    tableData.value = res.data.data
  }).catch(err => {
    ElMessage.error(err.message)
  })
}//溯源新增
const handleAdd = () => {
  addIds.value = []
  imageUrl.value = ""
  ///清空表单
  AddForm.value.rabit_Id = 0
  AddForm.value.sId = 0
  AddForm.value.rabit_Batch = ""
  AddForm.value.rabit_Shelflife = 0
  AddForm.value.rabit_Shencan = ""
  AddForm.value.rabit_Company = ""
  AddForm.value.rabit_Infomation = ""
  AddForm.value.rabit_TitleImg = ""
  AddForm.value.rabit_IsDel = false
  AddForm.value.creater = ""
  AddForm.value.updater = ""
  bt.bname = "新增"
  bt.Titlename = "溯源管理-新增"
  bt.bsf=false
    dialogVisible.value = true
      BatchShow()
}//溯源提交
const onSubmit = () => {
  if (bt.bname == "新增") {
        if (isNaN(AddForm.value.rabit_Shelflife) ) {
    ElMessage.error("生产日期只能为数字")
       return
  }
    AddForm.value.rabit_Id = 0
    axios.post("http://localhost:5094/api/RabitsAll/AddRaibts", AddForm.value).then(res => {
      if (res.data.code > 0) {
        ElMessage.success(res.data.message)
        dialogVisible.value = false
        addIds.value = []
        ///清空表单
        AddForm.value.rabit_Id = 0
        AddForm.value.sId = 0
        AddForm.value.rabit_Batch = ""
        AddForm.value.rabit_Shelflife = 0
        AddForm.value.rabit_Shencan = ""
        AddForm.value.rabit_Company = ""
        AddForm.value.rabit_Infomation = ""
        AddForm.value.rabit_TitleImg = ""
        AddForm.value.rabit_IsDel = false
        AddForm.value.creater = ""
        AddForm.value.updater = ""
        Show()
      }
      else {
        ElMessage.error(res.data.message)
        Show()
      }
    })
  }
  else {
           if (isNaN(AddForm.value.rabit_Shelflife) ) {
    ElMessage.error("生产日期只能为数字")
       return
  }
    AddForm.value.rabit_Id = bt.bid
    AddForm.value.updater = localStorage.getItem("Name") ?? ""
    axios.post("http://localhost:5094/api/RabitsAll/EditRaibts", AddForm.value).then(res => {
      if (res.data.code > 0) {
        ElMessage.success(res.data.message)
        dialogVisible.value = false
        addIds.value = []
        ///清空表单
        AddForm.value.rabit_Id = 0
        AddForm.value.sId = 0
        AddForm.value.rabit_Batch = ""
        AddForm.value.rabit_Shelflife = 0
        AddForm.value.rabit_Shencan = ""
        AddForm.value.rabit_Company = ""
        AddForm.value.rabit_Infomation = ""
        AddForm.value.rabit_TitleImg = ""
        AddForm.value.rabit_IsDel = false
        AddForm.value.creater = ""
        AddForm.value.updater = ""
        Show()
      }
      else {
        ElMessage.error(res.data.message)
        Show()
      }
    })
  }
}
//溯源修改
const handleEdit = (row: any) => {
  bt.bid = row.id
  bt.bname = "修改"
  bt.Titlename = "溯源管理-修改"
  bt.bsf=false
  dialogVisible.value = true
  ContentEdit(row.rabit_Batch)
}//溯源下拉框列表
const ShowShop = () => {
  axios.get('http://localhost:5094/api/RabitsAll/ShowShop').then(res => {
    options.value = res.data.data
  })
}
//填充数据
const ContentEdit = (Bath: any) => {
  axios.get("http://localhost:5094/api/RabitsAll/FirstRabits", {
    params: {
      Batch: Bath
    }
  }).then(res => {
    AddForm.value = res.data.data
    imageUrl.value = AddForm.value.rabit_TitleImg
  })
}
//保存选中的id
const handleSelectionChange = (selection: any[]) => {
  addIds.value = selection.map(item => item.rabit_Id)
}//删除所有选中数据
const AllDel = () => {
  if (addIds.value.length == 0) {
    ElMessage.error("请选择要删除的记录")
    return;
  }
  if (!confirm("确认已选中要删除的" + addIds.value.length + "个溯源商品吗？"))
    return;
  axios.get('http://localhost:5094/api/RabitsAll/DelAllRabits', {
    params: {
      ids: addIds.value.join(',')
    }
  })
    .then(res => {
      if (res.data.code > 0) {
        ElMessage.success(res.data.message)
        Show()
        addIds.value = []
      } else {
        ElMessage.error(res.data.message)
      }
    })
}//删除单数据
const handleDelete = (sid: number) => {
  if (!confirm("确认删除溯源商品吗？"))
    return;
  axios.get('http://localhost:5094/api/RabitsAll/DelRaibts', {
    params: {
      id: sid
    }
  })
    .then(res => {
      if (res.data.code > 0) {
        ElMessage.success(res.data.message)
        Show()
      } else {
        ElMessage.error(res.data.message)
      }
    })

}
//跳转并传值到详情页
const RabitsDetail = (row: any) => {
  window.location.href = "/ShowRabitsDetail?Batch=" + row.rabit_Batch
}
//打开导出溯源码弹窗
const ExportEdit = () => {
  LogExport.value = true
}
const AllExport = () => {
  let url = "http://localhost:5094/api/ExportAll/Export?NumCout=" + ExportCouts.value.cout;
  window.location.href = url
  LogExport.value = false
}
//自动生成的批次号
const BatchShow=()=>{
axios.get("http://localhost:5094/api/RabitsAll/BathShow")
.then(res=>{
  AddForm.value.rabit_Batch=res.data.data
})
}
</script>
<!-- 使用黑色实线边框,增大加号，加粗边框 -->
<style>
.avatar-uploader .el-upload {
  border: 5px solid var(--el-border-color);
  border-color: black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 150px;
  color: black;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>